﻿/*
Copyright © Naveen Hegde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name of the author, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written 
permission. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;

namespace NvinInstaller
{
    public class WixManager
    {
        public static void Compile()
        {
            //Validate input values
            if (Validate() == false)
            {
                return;
            }
            // genereate wix file
            WixFileGenerator.GenerateWixFile(ApplicationManager.GetApplicationManager());
            // compile wix file
            WixCompiler.Compile();
        }

        #region Validation
        private static bool Validate()
        {
            //Project properties
            bool projectProp = ValidateProjectProperties();
            bool appDir = ValidateApplicationDir();
            bool projectMenu = ValidateProjectMenu();
            bool registry = ValidateRegistry();
            bool other = VidateOtherOptions();

            return projectProp && projectMenu && appDir && registry && other;
        }

        private static bool ValidateProjectProperties()
        {
            bool status = true;

            ProjectProperties properties = ApplicationManager.GetApplicationManager().Properties;
            if (String.IsNullOrEmpty(properties.Comments))
            {
                Logger.AddOutputMessage("No comment is provided by the user.", LogType.Warning);
            }
            if (String.IsNullOrEmpty(properties.Description))
            {
                Logger.AddOutputMessage("No description is provided by the user.", LogType.Warning);
            }
            if (String.IsNullOrEmpty(properties.LicenseFile))
            {
                Logger.AddOutputMessage("No License file selected.", LogType.Error);
                status = false;
            }
            if (String.IsNullOrEmpty(properties.LicenseFile) == false && File.Exists(properties.LicenseFile) == false)
            {
                Logger.AddOutputMessage("License file not found.", LogType.Error);
                status = false;
            }
            if (String.IsNullOrEmpty(properties.Manufacturer))
            {
                Logger.AddOutputMessage("Manufacturer name is not available.", LogType.Warning);
            }
            if (String.IsNullOrEmpty(properties.OutputFile))
            {
                Logger.AddOutputMessage("Output file location is not available.", LogType.Error);
                status = false;
            }
            if (String.IsNullOrEmpty(properties.ProductName))
            {
                Logger.AddOutputMessage("Product name is not available.", LogType.Error);
                status = false;
            }
            if (String.IsNullOrEmpty(properties.Version))
            {
                Logger.AddOutputMessage("Invalid version number.", LogType.Error);
                status = false;
            }
            if (properties.Version != null)
            {
                string[] version = properties.Version.Split(".".ToCharArray());
                if (version.Length == 0)
                {
                    Logger.AddOutputMessage("Invalid version number.", LogType.Error);
                    status = false;
                }
                foreach (string val in version)
                {
                    int number;
                    if (int.TryParse(val, out number) == false)
                    {
                        Logger.AddOutputMessage("Given version number is not in valid format.Version number is expected in 'n.[n].[n].[n]' format.", LogType.Error);
                        status = false;
                    }
                }
            }
            if (properties.UserInterfaceType == UIType.Complete || properties.UserInterfaceType == UIType.FeatureTree)
            {
                if (properties.Features.Count == 0)
                {
                    Logger.AddOutputMessage("Selected user interface type requires atleast one feature to be defined.", LogType.Error);
                    status = false;
                }
            }
            return status;
        }

        private static bool ValidateApplicationDir()
        {
            return ValidateFeatures();
        }

        private static bool ValidateFeatures()
        {
            bool status = true;
            TreeView appTree = ApplicationManager.GetApplicationManager().ApplicationTree;
            ProjectProperties properties = ApplicationManager.GetApplicationManager().Properties;
            foreach (TreeNode node in appTree.Nodes)
            {
                if (FeatureExists((ApplicationDirectoryNode)node,properties) == false)
                {
                    Logger.AddOutputMessage(node.FullPath + " feature value is not valid", LogType.Error);
                    status = false;
                }
                if (node.Nodes.Count != 0)
                {
                    foreach (TreeNode childNode in node.Nodes)
                    {
                        status = ValidateChildNodeFeature(childNode, properties) && status;
                    }
                }
            }
            return status;
        }

        private static bool ValidateChildNodeFeature(TreeNode childNode, ProjectProperties properties)
        {
            bool status = true;
            if (FeatureExists((ApplicationDirectoryNode)childNode, properties) == false)
            {
                Logger.AddOutputMessage(childNode.FullPath + " feature value is not valid", LogType.Error);
                status = false;
            }
            if (childNode.Nodes.Count > 0)
            {
                foreach (TreeNode node in childNode.Nodes)
                {
                    status = ValidateChildNodeFeature(node, properties) && status;
                }
            }
            return status;
        }

        private static bool FeatureExists(ApplicationDirectoryNode appNode, ProjectProperties properties)
        {
            if (appNode.Type == ApplicationDirNodeType.File)
            {
                foreach (Feature feature in properties.Features)
                {
                    if (feature.Name.Equals(((Component)appNode.Content).Feature))
                    {
                        return true;
                    }
                }
            }
            else
            {
                return true;
            }
            return false;
        }

        private static bool ValidateProjectMenu()
        {
            return true;
        }

        private static bool ValidateRegistry()
        {
            return true;
        }

        private static bool VidateOtherOptions()
        {
            // check Images
            if (File.Exists(Globals.WixFolder + Path.DirectorySeparatorChar + "Bitmaps" + Path.DirectorySeparatorChar + "bannrbmp.bmp") == false
                || File.Exists(Globals.WixFolder + Path.DirectorySeparatorChar + "Bitmaps" + Path.DirectorySeparatorChar + "dlgbmp.bmp") == false)
            {
                Logger.AddOutputMessage("Dialog images are missing. Please reconfigure dialog images or reinstall this application", LogType.Error);
            }
            return true;
        }
        #endregion
    }
}
